<!doctype html>
<html lang=en>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Graph</title>
	<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.8.6/dist/protobuf.js"></script>
	<script src="js/graph.js"></script>

	<style>
		html, body {
			width:  100%;
			height: 100%;
			margin: 0;
			overflow: hidden;
		}

		button {
		     margin-top: 1px;
		     margin-right: 2px;
		     position:absolute;
		     top:0;
		     right:0px;
		}
	</style>

</head>
<body>


<canvas id="myCanvas" onmousedown="mouseDown()" onmouseup="mouseUp()" onmousemove="mouseMove(event)">
Your browser does not support the HTML5 canvas tag.
</canvas>

<button type="button" onclick="periodic_graph_request()">Auto Refresh</button>

</body>
<script type="text/javascript">
	
	var mouse_down = false;
	var scroll_time;
	var interval;
	var prev_pos;

	var proto_grath;
	var proto_axis;
	var proto_array;
	var array_buffer;

	var my_graph = new spn_graph(70, "myCanvas");

	var file_reader = new FileReader();

	function periodic_graph_request() {
		graph_request();
		
		if (typeof interval === 'undefined') {
			interval = setInterval(graph_request, 2000);
		}
		
	}

	function graph_request(time) {

		time = time || 0;
		//JSon request
		var request = { "command" : "get graph", 
				"spn" : spn,
				"id" : id,					
				"period" : 100000,
				"samples" : 500,
				"time" : time			
				 };
		var jsonReq = JSON.stringify(request);
		webSocket.send(jsonReq);
	}


	function mouseDown() {
		console.log("mouseDown");

		var spec = my_graph.get_xspec();

		//Graph not printed even once
		if (typeof spec === 'undefined') {
			return;
		}

		mouse_down = true;
		
		prev_pos = {x: event.clientX, y: event.clientY};

		scroll_time = spec.max;

		//Do not show plots, only the axis which change
		my_graph.clear_plots();
		
		//Stop periodic request
		if (typeof interval !== 'undefined') {
			clearInterval(interval);
			interval =  undefined;
		}
	}

	function mouseUp() {
		console.log("mouseUp");
		
		if(mouse_down) {
			
			//Refresh the graph with the correct time
			graph_request(scroll_time);
			mouse_down = false;
		}

	}

	function mouseMove(event) {
		console.log("mouseMove");
		if(mouse_down) {
			var spec = my_graph.get_xspec();
			var graphRect = my_graph.get_graphRect();
			var diff_time = spec.max - spec.min;
			scroll_time = diff_time * (prev_pos.x - event.clientX) / graphRect.w + spec.max;

			//Modify graph spec reference directly
			spec.min = scroll_time - diff_time;			
			spec.max = scroll_time;

			//Do not show plots, only the axis which change
			my_graph.draw();

			prev_pos = {x: event.clientX, y: event.clientY};

		}

	}

	function findGetParameter(parameterName) {
		var result = null,
		tmp = [];
		location.search
		.substr(1)
		.split("&")
		.forEach(function (item) {
			tmp = item.split("=");
			if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
		});
		return result;
	}

	

	file_reader.onload = function(event) {
		array_buffer = event.target.result;
		proto_array = new Uint8Array(array_buffer);
		// Decode an Uint8Array
		try {
			var message = proto_grath.decode(proto_array);
			drawGraph(message);
			return;
		} catch (e) {
			//Not a graph message
		}

		try {
			var message = proto_axis.decode(proto_array);
			return;
		} catch (e) {
			//Not an axis message
		}

	};


	protobuf.load("graph.proto", function(err, root) {
		if (err) 
			throw err;
	
		// Obtain a message type
		proto_grath = root.lookupType("Graph");
		proto_axis = root.lookupType("Axis");

	});


	//Get get parameters (everything is verified in server side, we just forward)
	var spn = Number(findGetParameter("spn"));
	var id = Number(findGetParameter("id"));

	document.title = "SPN " + spn;

	var webSocket;

	var hostName = window.location.hostname;

	if(hostName.length == 0) { hostName = "127.0.0.1"; }
    
    	console.log("openWSConnection::Connecting to --> ws://" + hostName + ":8000");
    	try {

		webSocket = new WebSocket("ws://" + hostName + ":8000", "graph-protocol");
		webSocket.onopen = function(openEvent) {

		    	console.log("WebSocket OPEN: " + JSON.stringify(openEvent, null, 4));

			//Request graph painting every 2000 millis

			interval = setInterval(graph_request, 2000);
		   
		};

		webSocket.onclose = function (closeEvent) {

		    console.log("WebSocket CLOSE: " + JSON.stringify(closeEvent, null, 4));
		    
		};

		webSocket.onerror = function (errorEvent) {
		    console.log("WebSocket ERROR: " + JSON.stringify(errorEvent, null, 4));
		};

		webSocket.onmessage = function (messageEvent) {

			console.log("WebSocket MESSAGE received");

			file_reader.readAsArrayBuffer(messageEvent.data);


		};
		

    	} catch (exception) {
		console.error("Error " + exception.message);
    	}


	function drawGraph(message) {
		
		if(message.samples.length == 0) {
			return;
		}

		my_graph.set_xspec(message.axisX);
		my_graph.set_yspec(message.axisY);

		my_graph.set_plots(message.samples.map(
		
			function(value) {
				return [value.x, value.y];
			}
		));

		my_graph.draw();

	}


</script>

</html>
